#! /bin/sh

set -e

grepconf () {
	w=" 	" # space tab
	# sed is cool.
	res=`squid3 -k parse 2>&1 |
		grep "Processing:" |
		sed s/.*Processing:\ // |
		sed -ne '
			s/^'$1'['"$w"']\+\([^'"$w"']\+\).*$/\1/p;
			t end;
			d;
			:end q'`
	[ -n "$res" ] || res=$2
	echo "$res"
}

grepconf2 () {
	w=" 	" # space tab
	# sed is cool.
	res=`squid3 -k parse 2>&1 |
		grep "Processing:" |
		sed s/.*Processing:\ // |
		sed -ne '
			s/^'$1'['"$w"']\+[^'"$w"']\+['"$w"']\+\([^'"$w"']\+\).*$/\1/p;
			t end;
			d;
			:end q'`
	[ -n "$res" ] || res=$2
	echo "$res"
}

case "$1" in
	configure)
		#
		# Chown the directories.
		#
		log_dir=/var/log/squid3
		cache_dir=`grepconf2 cache_dir /var/spool/squid3`
		usr=`grepconf cache_effective_user proxy`
		grp=`grepconf cache_effective_group proxy`

		if [ "$(stat -c %U $cache_dir)" != "$usr" ] ||
		   [ "$(stat -c %G $cache_dir)" != "$grp" ] ; then
			chown $usr:$grp $cache_dir -R
		fi

		if [ "$(stat -c %U $log_dir)" != "$usr" ] ||
		   [ "$(stat -c %G $log_dir)" != "$grp" ] ; then
			if [ "$(dpkg-statoverride --list $log_dir)" = "" ] ; then
		  		chown -R $usr:$grp $log_dir
			fi
		fi

		#
		# Create spool dirs if they don't exist.
		#
		if [ -d "$cache_dir" -a ! -d "$cache_dir/00" ]
		then
			echo "Creating Squid HTTP proxy 3.x spool directory structure"
			squid3 -z
		fi

		#
		# Remove obsolete manager ACL definition.
		# It will halt upgrade with fatal error if left.
		#
		if test -f /etc/squid3/squid.conf && dpkg --compare-versions "$2" lt '3.4' && grep -q "^[[:blank:]]*acl manager" /etc/squid3/squid.conf ; then
			echo "Filtering squid.conf manager ACL."
			cp /etc/squid3/squid.conf /etc/squid3/squid.conf.pre_3.4_upgrade
			sed -e "s/^\([ \t]*acl manager.*\)/# \1 # Commented out on upgrade to 3.4/" </etc/squid3/squid.conf.pre_3.4_upgrade >/etc/squid3/squid.conf
		fi
		;;
	abort-upgrade)
		#
		# Revert the automated configuration changes we may have done
		#
		if test -f /etc/squid3/squid.conf.pre_3.4_upgrade; then
			echo "Removing squid.conf changes."
			mv /etc/squid3/squid.conf.pre_3.4_upgrade /etc/squid3/squid.conf
		fi
		exit 0
		;;
	abort-remove|abort-deconfigure)
		;;
	*)
		#
		#	Unknown action - do nothing.
		#
		exit 0
		;;
esac

#
#	Update links if needed and start squid3.
#
update-rc.d squid3 defaults 30 >/dev/null

invoke-rc.d squid3 restart

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0
